import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

// 团队成员接口定义
interface TeamMember {
  id?: string
  projectId: string
  name: string
  email: string
  phone?: string
  department?: string
  position?: string
  role: string
  joinDate?: string
  leaveDate?: string
  status: string
  responsibilities?: string
  skills?: string[]
  avatar?: string
  createdBy: string
}

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const project = await db.researchProject.findUnique({
      where: { id: (await params).id },
      select: {
        teamMembers: true
      }
    })
    
    if (!project) {
      return NextResponse.json(
        { error: 'Research project not found' },
        { status: 404 }
      )
    }
    
    const teamMembers = project.teamMembers ? JSON.parse(project.teamMembers) : []
    
    return NextResponse.json({
      teamMembers,
      count: teamMembers.length
    })
  } catch (error) {
    console.error('Error fetching project team:', error)
    return NextResponse.json(
      { error: 'Failed to fetch project team' },
      { status: 500 }
    )
  }
}

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const body = await request.json()
    
    // 验证项目是否存在
    const project = await db.researchProject.findUnique({
      where: { id: (await params).id }
    })
    
    if (!project) {
      return NextResponse.json(
        { error: 'Research project not found' },
        { status: 404 }
      )
    }

    const {
      name,
      email,
      phone,
      department,
      position,
      role,
      joinDate,
      leaveDate,
      status,
      responsibilities,
      skills,
      avatar,
      createdBy
    }: TeamMember = body

    // 验证必填字段
    if (!name || !email || !role || !status || !createdBy) {
      return NextResponse.json(
        { error: 'Missing required fields: name, email, role, status, createdBy' },
        { status: 400 }
      )
    }

    // 获取现有团队成员
    const existingTeamMembers = project.teamMembers ? JSON.parse(project.teamMembers) : []
    
    // 创建新成员
    const newMember: TeamMember = {
      id: `member-${Date.now()}`,
      projectId: (await params).id,
      name,
      email,
      phone: phone || '',
      department: department || '',
      position: position || '',
      role,
      joinDate: joinDate || new Date().toISOString(),
      leaveDate: leaveDate || null,
      status,
      responsibilities: responsibilities || '',
      skills: skills || [],
      avatar: avatar || '',
      createdBy,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }

    // 添加到团队成员列表
    const updatedTeamMembers = [...existingTeamMembers, newMember]

    // 更新项目的团队成员信息
    const updatedProject = await db.researchProject.update({
      where: { id: (await params).id },
      data: {
        teamMembers: JSON.stringify(updatedTeamMembers),
        updateTime: new Date()
      },
      include: {
        creator: {
          select: {
            id: true,
            name: true,
            email: true
          }
        },
        updater: {
          select: {
            id: true,
            name: true,
            email: true
          }
        }
      }
    })

    // 创建历史记录
    await db.projectHistory.create({
      data: {
        projectId: (await params).id,
        action: 'TEAM_MEMBER_ADDED',
        description: `添加团队成员: ${name} (${role})`,
        userId: createdBy,
        fromLevel1: project.level1,
        fromLevel2: project.level2,
        toLevel1: project.level1,
        toLevel2: project.level2
      }
    })

    return NextResponse.json(newMember)
  } catch (error) {
    console.error('Error creating team member:', error)
    return NextResponse.json(
      { error: 'Failed to create team member' },
      { status: 500 }
    )
  }
}

export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const body = await request.json()
    const { 
      teamMembers, 
      updatedBy 
    } = body
    
    const existingProject = await db.researchProject.findUnique({
      where: { id: (await params).id }
    })
    
    if (!existingProject) {
      return NextResponse.json(
        { error: 'Research project not found' },
        { status: 404 }
      )
    }
    
    const project = await db.researchProject.update({
      where: { id: (await params).id },
      data: {
        teamMembers: teamMembers ? JSON.stringify(teamMembers) : null,
        updatedBy,
        updateTime: new Date()
      },
      include: {
        creator: {
          select: {
            id: true,
            name: true,
            email: true
          }
        },
        updater: {
          select: {
            id: true,
            name: true,
            email: true
          }
        }
      }
    })
    
    // 创建历史记录
    await db.projectHistory.create({
      data: {
        projectId: project.id,
        action: 'TEAM_UPDATED',
        description: `更新团队成员信息`,
        userId: updatedBy,
        fromLevel1: existingProject.level1,
        fromLevel2: existingProject.level2,
        toLevel1: project.level1,
        toLevel2: project.level2
      }
    })
    
    return NextResponse.json(project)
  } catch (error) {
    console.error('Error updating project team:', error)
    return NextResponse.json(
      { error: 'Failed to update project team' },
      { status: 500 }
    )
  }
}